package com.xuxueli.commontdemo.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpStatus;

import java.io.Serializable;
import java.util.HashMap;

/**
 * 响应请求数据模型
 *
 */
public class ResponseResult extends HashMap<String, Object> implements Serializable {

	private static final long serialVersionUID = 1538422593960745870L;

	public static final int SUCCESS_CODE = 200;
	public static final int NO_DATA_CODE = 1;
	public static final int FAIL_CODE = HttpStatus.SC_INTERNAL_SERVER_ERROR;

	public ResponseResult() {
		put("code", SUCCESS_CODE);
		put("message", "success");
	}

	public ResponseResult(String message) {
		put("code", SUCCESS_CODE);
		put("message", message);
	}


	public static ResponseResult error() {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
	}

	public static ResponseResult error(String message) {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, message);
	}

	public static ResponseResult error(int code, String message) {
		ResponseResult responseResult = new ResponseResult();
		responseResult.put("code", code);
		responseResult.put("message", message);
		return responseResult;
	}

	public static ResponseResult ok(String message) {
		return new ResponseResult(message);
	}

	public static ResponseResult ok(int code, String message) {
		ResponseResult responseResult = new ResponseResult();
		/*r.put("code", code);
		r.put("message", message);*/
		return responseResult;
	}

	public static ResponseResult ok() {
		return new ResponseResult();
	}

	public ResponseResult put(String key, Object value) {
		super.put(key, value);
		return this;
	}

	/**
	 * 设置响应数据
	 * @param data
	 * @return
	 */
	public ResponseResult putData(Object data) {
		return put("data", data);
	}

	public Integer getCode() {
		return (Integer) get("code");
	}

	public String getmessage() {
		return (String) get("message");
	}

	public Object getData() {
		return get("data");
	}

	public JSONObject getDataForJSONObject() {
		Object data = getData();
		if(data == null) {
			return null;
		}

		return (JSONObject) JSONObject.toJSON(data);
	}

	public JSONArray getDataForJSONArray() {
		Object data = getData();
		if(data == null) {
			return null;
		}

		return (JSONArray) JSONArray.toJSON(data);
	}

	public JSONObject toJSONObject() {
		return new JSONObject(this);
	}

	public String toJSONString() {
		return toJSONObject().toJSONString();
	}

}
